import datetime
import json
import os
import re

import redis
import requests
from flask import Blueprint, make_response, request, jsonify, redirect
import random
from db import db1, DB
from utils.captcha.captcha import captcha
from utils.jwttoken import myjwt
from utils.mailbox import Phone_Code
from utils.rbac import RBAC

background_view = Blueprint('background_view', __name__)


# ..................................后端..................................
# 管理员登录
@background_view.route('/Administrator_login', methods=['POST'])
def Administrator_login():
    username = request.form.get('username')
    password = request.form.get('password')
    db = DB()
    res = db.get_one("select id,username,password from user where username='%s'" % username)
    if str(username) == str(res['username']) and str(password) == str(res['password']):
        return jsonify({'code': 200, 'msg': '登陆成功','id':res['id'],'username':res['username']})
    else:
        return jsonify({'code': 403, 'msg': '用户名或密码不正确'})


# 添加题目
@background_view.route('/addassess', methods=['POST', 'GET'])
def addassess():
    data = request.json
    dict1 = {}
    for (j, value) in data.items():
        if j[:-1] == 'answer':
            key = str(value).split(" ")[0]
            dict1[key] = value[2:]
    list = []
    print("insert into assess_topic (topic,answer) values ('%s','%s')" % (data['dopic0'], dict1))
    # try:
    sql = "insert into assess_topic (topic,answer) values ('%s','%s')" % (data['dopic0'], json.dumps(dict1))
    db1.update(sql)
    return jsonify({'code': 200, 'msg': '添加成功'})

    # 获取标地列表


@background_view.route('/marklist')
def marklist():
    sql = "select * from mark0 where status=1 union all " \
          "select * from mark1 where status=1 union all " \
          "select * from mark2 where status=1"
    res = db1.find_all(sql)
    return jsonify({'code': 200, 'list': res})


# 审核标地
@background_view.route('/markaudit')
def markaudit():
    markid = request.args.get('markid')
    print(markid)
    status = request.args.get('status')
    number = int(markid) % 3
    sql = "update mark%d set status=%d where id=%d" % (number, int(status), int(markid))
    db1.update(sql)
    num = random.randint(1000, 9999)
    order_number = str(datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S')) + str(num)
    # 如果满标审核拒绝的话
    if int(status)==5:
        res=db1.get_all("select * from recordbid where Investment_id=%d" % int(markid))
        for i in res:
            # 冻结资金释放,退还给各个用户并增添订单,标注退款
            # 1为冻结资金2为释放资金3为退款资金

            db1.update("update recordbid set state=%d where id=%d" % (3, int(i['id'])))

            # 更改余额资金
            db1.update('update user set money=money+%s where id=%d' % (float(i['money']), int(i['userid'])))
            # balance账户余额

            res5=db1.get_one("select * from user where id=%s" % int(i['userid']))

            # 增添订单详情
            db1.insert(
                "insert into order_details (order_number,money,state,balance,userid,stats) values ('%s',%s,5,%s,%s,1)" % (
                    order_number, float(i['money']), float(res5['money']), int(i['userid'])))
    # 如果满标审核通过的话
    if int(status) == 4:
        res9 = db1.get_one('select * from mark%d where id=%d and status=4 and balance_money=0' % (number, int(markid)))
        # need_money
        db1.update('update user set money=money+%s where id=%d' % (float(res9['need_money']), int(res9['userid'])))
        # 增添订单详情
        res5 = db1.get_one("select * from user where id=%s" % int(res9['userid']))
        db1.insert(
            "insert into order_details (order_number,money,state,balance,userid,stats) values ('%s',%s,4,%s,%s,1)" % (
                order_number, float(res9['need_money']), float(res5['money']), int(res9['userid'])))
        res = db1.get_all("select * from recordbid where Investment_id=%d" % int(markid))
        for i in res:
            # 将冻结资金改为释放资金
            db1.update("update recordbid set state=%d where id=%d" % (2, int(i['id'])))
    return jsonify({'code': 200, 'msg': '审核完成'})


# 获取审核员的权限
@background_view.route('/background_resurce')
def background_resurce():
    uid = request.args.get('uid')
    db = DB()
    data = db.get_all('select * from user where id=%s and roleid=2' % uid)
    list = []
    list2 = []
    dict = {}
    if data:
        num_data = db.get_all('select * from background_resurce ')

        for i in num_data:
            dict[i['id']] = i
        for j in num_data:
            pid = j['pid']
            grade = j['grade']
            #  pid等于0，就是顶级，
            if pid == None:
                # 直接加入列表
                list.append(j)
            # if grade==2 or pid==3:
            #     list2.append(j)
            else:
                #  查看父类是否有子类

                if 'son' not in dict[pid]:
                    dict[pid]['son'] = []
                dict[pid]['son'].append(j)
        return ({'code': '200','list':list,'list2':list2})
    else:
        return ({'code': '403', 'msg': '您没权限'})
